package com.jgsu.farm.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jgsu.farm.entity.BiologyCategory;
import com.jgsu.farm.entity.PestStress;
import com.jgsu.farm.entity.Plant;
import com.jgsu.farm.exception.*;
import com.jgsu.farm.mapper.*;
import com.jgsu.farm.mapper.sql.BiologyMapperSql;
import com.jgsu.farm.mapper.sql.PlantMapperSql;
import com.jgsu.farm.service.PlantService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
@Slf4j
@Service
public class PlantServiceImpl implements PlantService {
    @Autowired
    private BiologyCategoryMapper biologyCategoryMapper;
    @Autowired
    private PlantMapper plantMapper;
    @Autowired
    private PlantMapperSql plantMapperSql;

    @Autowired
    private RedisTemplate redisTemplate;


//------------------------------------------------------------------

    @Override
    public void addPlant(Plant plant) {
        log.info("id为:{},名字为{}",plant.getCategory(),plant.getChinesename());
        // 先从获取的category与进行查询category表是否有以及image表是否有该imageId，查询成功才能插入语
        BiologyCategory biologyCategory = biologyCategoryMapper.selectByPrimaryKey(plant.getCategory());
        if (biologyCategory != null) {
            plantMapper.insert(plant);
        } else {
            throw new DataAddException("604", "插入的category在category表中没有，请先插入到category表");
        }
    }

    /**
     * 根据id删除作物信息功能
     */
    @Override
    public void deletePlant(Integer plantid) {
        Integer plantId = plantMapper.deleteByPrimaryKey(plantid);
        if (plantId == 0 || plantId == null) {
            throw new DataNotExistException("603", "不存在该id作物删除失败");
        }
    }

    /**
     * 修改作物信息
     */
    @Override
    public void updatePlant(Plant plant) {
        BiologyCategory biologyCategory = biologyCategoryMapper.selectByPrimaryKey(plant.getCategory());
        if (biologyCategory != null) {
            plantMapper.updateByPrimaryKey(plant);
        } else {
            throw new DataNotExistException("603", "修改作物信息时，没有该植物分类请先在分类表中更新");
        }

    }


    /**
     * 分页查询
     * 缓存穿透：当 key 的数据源并不存在,因为数据源不存在,所以在缓存中也是不存在的,
     *           这样每次请求这个没有key 的数据,每次都会请求数据库,如果大量高并发请求过来,可能会压垮数据库;
     */
    @Override
    public PageInfo<Plant> getPlantPages(int page, int pagesize) {
        PageHelper.startPage(page, pagesize);
        // 查询redis中是否存在
        List<Plant> plants = (List<Plant>) redisTemplate.opsForValue().get("plants");
        // 双重检测锁机制，解决缓存穿透问题，从而处理高并发要求
        if (null == plants) {
            synchronized (this) {
                plants = (List<Plant>) redisTemplate.opsForValue().get("plants");
                if (null == plants) {
                    plants = plantMapperSql.selectPlantListWithBiologyCategory();
                    log.info("从数据库中查询。。。。");
                    redisTemplate.opsForValue().set("plants", plants);
                    log.info("将从数据库中查询的plants数据存入redis。。。。");
                }
            }
        }
        PageInfo<Plant> pageInfoPlants = new PageInfo<Plant>(plants);
        log.info("从redis缓存中查询plant中的信息。。。。");
        return pageInfoPlants;
    }

    //------------------------------------------------------------------
    @Override
    public Plant selectPlant(Integer plantid) {
        Plant plant = plantMapper.selectByPrimaryKey(plantid);
        if (plant == null){
            throw new DataNotExistException("400", "不存在该植物信息");
        }else {
            return plant;
        }
    }

    /**
     * 该方法专门根据植物名(plantname)查询plantID
     */
    @Override
    public int findPlantId(String chinesename) {
        Integer plantid = plantMapperSql.findId(chinesename);
        if (plantid != null) {
            return plantid;
        } else {
            throw new DataNotExistException("400", "不存在该植物信息");
        }
    }

    /**
     * 修改作物名字
     */
    @Override
    public void updateNameById(Integer plantid) {
        //1.先根据id查询是否存在该数据
        Plant plant = plantMapperSql.selectPlantById(plantid);
        //2.在修改数据里的内容
        if (plant != null) {
            plantMapperSql.updateNameById(plantid);
        } else {
            throw new DataNotExistException("603", "id不存在，更新失败");
        }
    }
}
